<template>
  <div class="title">防抖和节流(Debounce & Throttle)</div>
  <div class="inner">
    <el-form>
             <el-form-item label="模拟普通搜索" >
             <el-input v-model="strNumber"/>
             </el-form-item>
             <el-form-item label="模拟防抖(Debounce)" >
             <el-input v-model="strNumberDebounce"/>
             </el-form-item>
             <el-form-item label="模拟节流(Throttle)" >
             <el-input v-model="strNumberThrottle"/>
             </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {ref,watch} from 'vue'
import { ElMessage } from 'element-plus'

let strNumber=ref(''),strNumberDebounce=ref(''),strNumberThrottle=ref('');
//模拟普通搜索
watch(
    ()=>strNumber.value,
    (newValue,oldValue)=>{
    ElMessage({
     message: '你要搜索的值是：'+newValue,
     type: 'success',
   })
}
)

//模拟防抖(Debounce)
const modelHandleDebounce=handleDebounce((vaIn)=>{
    ElMessage({
     message: '你要搜索的值是：'+vaIn,
     type: 'success',
   })
},2000)
watch(
    ()=>strNumberDebounce.value,
    (newValue,oldValue)=>{
    modelHandleDebounce(newValue)
}
)

//模拟节流(Throttle)
const modelHandleThrottle=handleThrottle((vaIn)=>{
    ElMessage({
     message: '你要搜索的值是：'+vaIn,
     type: 'success',
   })
},2000)
watch(
    ()=>strNumberThrottle.value,
    (newValue,oldValue)=>{
    modelHandleThrottle(newValue)
}
)
// Debounce (防抖): 每次触发事件时设置延迟调用函数，在此期间取消以前触发的事件.
function handleDebounce(funcFollowIn, numDelayIn) {
    let timerInner = null;
    return (...args) => {
        if (timerInner) clearTimeout(timerInner);
        timerInner = setTimeout(() => {
            funcFollowIn.apply(this, args);
        }, numDelayIn);
    };
}
// Throttle (节流): 事件占用一个时间段, 在此时间段内不会再接受事件触发.
function handleThrottle(funcFollowIn, numDelayIn) {
    let timerInner = null;
    return (...args) => {
        if (!timerInner) {
            timerInner = setTimeout(() => {
                funcFollowIn.apply(this, args);
                timerInner = null;
            }, numDelayIn);
        }
    };
}

</script>

<style scoped>

::v-deep .el-form-item__label{
  font-size: 16px;
  font-weight: 500;
}
::v-deep .el-input__inner{
  width: 200px;
  color: black;
}
::v-deep .el-form-item__content{
  flex:0
}

</style>